package zl_service

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

type BarCodeHuntService struct {
}

type CommodityInfo struct {
	CommoditySubpic5 string `json:"commoditysubpic5"`
	Speclevel        string `json:"speclevel"`
	CommoditySubpic3 string `json:"commoditysubpic3"`
	CommoditySubpic4 string `json:"commoditysubpic4"`
	Attributecode2   string `json:"attributecode2"`
	CommoditySubpic1 string `json:"commoditysubpic1"`
	Attributecode1   string `json:"attributecode1"`
	CommoditySubpic2 string `json:"commoditysubpic2"`
	Attributecode3   string `json:"attributecode3"`
	Saleprice        string `json:"saleprice"`
	Spuname          string `json:"spuname"`
	Brandname        string `json:"brandname"`
	Attributevalue2  string `json:"attributevalue2"`
	Brandcode        string `json:"brandcode"`
	Attributevalue1  string `json:"attributevalue1"`
	Spucode          string `json:"spucode"`
	Skuname          string `json:"skuname"`
	Attributevalue3  string `json:"attributevalue3"`
	Skuspec          string `json:"skuspec"`
	CommodityMainpic string `json:"commoditymainpic"`
	Barcode          string `json:"barcode"`
}

type Response struct {
	Data      CommodityInfo `json:"data"`
	Success   string        `json:"success"`
	ErrorCode string        `json:"errorCode"`
	ErrorMsg  string        `json:"errorMsg"`
}

func (b *BarCodeHuntService) Hunt(barcode string) (error, *CommodityInfo) {
	remote_url := "http://yxlapp.zhonglunnet.com/zl.bs.cashapp.dcms.commodity.cloud.getskubybarcode.v5/1.0.0/action"
	client := &http.Client{}
	// 请求参数结构体，对应要发送的JSON数据格式
	requestData := struct {
		Barcode    string `json:"barcode"`
		AccountId  string `json:"account_id"`
		MtShopId   string `json:"mt_shop_id"`
		Appcode    string `json:"appcode"`
		AppVersion string `json:"app_version"`
	}{
		Barcode:    barcode,
		AccountId:  "595cf58e6e3044468fbfda957d0e2b4c20241115093307XV",
		MtShopId:   "YXL_APP_ACCOUNT_625875399_001_43f5185b-cc75-4a98-b3c7-21ad76d26a98",
		Appcode:    "POSASSISTANT_APP-001",
		AppVersion: "3.4.2",
	}
	bodyBytes, _ := json.Marshal(requestData)
	req, err := http.NewRequest("POST", remote_url, bytes.NewBuffer(bodyBytes))
	req.Header.Set("Content-Type", "application/json")
	if err != nil {
		return err, nil
	}
	body, err := client.Do(req)
	if err != nil {
		return err, nil
	}
	//将body
	res, err := ioutil.ReadAll(body.Body)
	if err != nil {
		return err, nil
	}
	var resp Response
	err = json.Unmarshal(res, &resp)
	if resp.Data.CommodityMainpic != "" {
		resp.Data.CommodityMainpic = "https://032001.zhonglunnet.com/" + resp.Data.CommodityMainpic
	}
	if err != nil {
		return err, nil
	}

	return nil, &resp.Data
}
